import 'package:asperm/tools/tools.dart';
import 'package:asperm/views/testing_steps_widget.dart';
import 'package:ffmpeg_kit_flutter_new/ffmpeg_kit.dart';
import 'package:ffmpeg_kit_flutter_new/return_code.dart';


import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:network_info_plus/network_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

import '../generated/l10n.dart';
import '../tools/configuration.dart';
import '../tools/const.dart';
import '../tools/motility.dart';
import '../tools/tcp_connection_service.dart';
import '../tools/video_saver_service.dart';
import '../tools/wifi_utils.dart';
import '../views/common_button.dart';
import 'dart:io';

import '../views/myDialog.dart';


enum Testing_steps {
  steps_1,
  steps_connect,
  steps_2_1,
  steps_2_2,
  steps_3,
  steps_liquify_countDown,
  steps_4,
  steps_5,
  steps_testing_in_process,
}
class Testing_Steps_Page extends StatefulWidget {
  const Testing_Steps_Page({super.key});

  @override
  State<Testing_Steps_Page> createState() => _Testing_Steps_PageState();
}

class _Testing_Steps_PageState extends State<Testing_Steps_Page> {

  final WifiUtils _wifiUtils = WifiUtils();
  late TcpConnectionService _tcpService;
  String _log = '';
  DeviceConnectionState _connectionStatus = DeviceConnectionState.disconnected;
  String _connectionStatusString = '';
  Testing_steps currentSteps =  Testing_steps.steps_1;
  MethodChannel _methodChannel = MethodChannel('my_channel');


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getNetworkInfo();


    WidgetsBinding.instance.addPostFrameCallback((_) {
      print('----addPostFrameCallback');
      getPermission();
    });
    setMethodChannel();

  }
  setMethodChannel(){
    _methodChannel.setMethodCallHandler((call) {
      if(call.method == 'MotilityAnalysisResult'){
        var result = call.arguments as Map;
        print('========= 精子活性分析结果：' + result.toString());

      }
      return Future(() => null);
    });

  }

  getPermission() async{

    bool permission = await getSavePhotoPermission();
    if (!permission){
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) {
            return customAlertDialog(
                title: S.of(context).kindTips,
                describe: S.of(context).turnOnPhotosServicesInSystem,
                leftStr: S.of(context).cancel,
                rightStr: S.of(context).goSettings,
                accountController: TextEditingController(),
                onTextChanged: (value) async {
                },
                sureFun: () {
                  Navigator.pop(context);
                  openAppSettings();
                },
                cancelFun: () {
                  Navigator.pop(context);
                });
          });

    }


  }


  getNetworkInfo() async {
    print('---------getNetworkInfo ');
    // 1. 申请必要权限
    final hasPermission = await _wifiUtils.requestRequiredPermissions();
    if (!hasPermission) {

      print('请授予位置权限以获取 Wi-Fi 信息');
      print('--------权限不足');
      return;
    }

    // 2. 检查位置服务（Android 10+ 必需）
    final isLocationEnabled = await _wifiUtils.isLocationServiceEnabled();
    if (!isLocationEnabled) {
      print('----请开启位置服务以获取 Wi-Fi 名称');

      // 引导用户开启位置服务
      final userAgreed = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text("需要位置服务"),
          content: const Text("Android 系统要求开启位置服务才能获取 Wi-Fi 名称，是否前往开启？"),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context, false),
              child: const Text("取消"),
            ),
            TextButton(
              onPressed: () => Navigator.pop(context, true),
              child: const Text("前往开启"),
            ),
          ],
        ),
      );

      if (userAgreed == true) {
        final isEnabled = await _wifiUtils.requestEnableLocationService();
        if (isEnabled) {

          print('---- 开启成功后重新加载');

        } else {
          print('---- 位置服务未开启');

        }
      }
      return;
    }



    final wifiName = await _wifiUtils.getProcessedWifiName();
    final ipAddress = await _wifiUtils.getWifiIpAddress();

    print('---------wifiName:${wifiName}');
    print('---------ipAddress:${ipAddress}');

    _initializeTcpService();
    if(wifiName != 'CameraAP'){
      _tcpService.connect();
      return;
    }

  }

  void _initializeTcpService() {

    _tcpService = TcpConnectionService(
      host: '192.168.3.1',
      port: 60011,
    );
    // 监听连接状态变化
    _tcpService.connectionStateStream.listen((state) {
      setState(() {
        _connectionStatus = state;
        switch (state) {
          case DeviceConnectionState.disconnected:
            _connectionStatusString = '已断开';
            break;
          case DeviceConnectionState.connecting:
            _connectionStatusString = '连接中...';
            break;
          case DeviceConnectionState.connected:
            _connectionStatusString = '已连接';
            break;
        }
        print('===状态变化: $_connectionStatusString');

      });
    });


    // 监听错误
    _tcpService.errorStream.listen((error) {
      setState(() {
        _addLog('====错误: $error');
      });
    });

    // 监听接收到的消息
    _tcpService.messageStream.listen((message) {
      print('===监听接收到的消息: $message');
    });
  }

  retryConnect(){
    _tcpService.dispose();
    _initializeTcpService();
    _tcpService.connect();
  }

  void _addLog(String message) {
    final timestamp = DateTime.now().toString().split(' ')[1];
    _log = '[$timestamp] $message\n$_log';
    if (_log.length > 1000) {
      _log = _log.substring(0, 1000);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xffF9F9F9),
        body: Container(
          height: screenHeight(context),
          child: Container(
            margin: EdgeInsets.only(top: appBarHeight(context)),
            width: double.infinity,
            color: Color(0xffF9F9F9),
            child: stepsWidget(),
          ),
        )
    );
  }

  stepsWidget(){

    switch (currentSteps) {
      case Testing_steps.steps_1: {
        return Steps_Widget(
          steps: currentSteps,
          nextAction:(){
            setState(() {
              currentSteps = Testing_steps.steps_connect;
            });
          },
          backAction: (){
            Navigator.pop(context);
          },
        );
       }
      case Testing_steps.steps_connect: {
        return steps_connect_widget(context);
       }
      case Testing_steps.steps_2_1: {
        return Steps_Widget(
          steps: currentSteps,
          nextAction:(){
            setState(() {
              currentSteps = Testing_steps.steps_2_2;
            });
          },
          backAction: (){
            setState(() {
              currentSteps = Testing_steps.steps_connect;
            });
          },
        );
      }
      case Testing_steps.steps_2_2: {
        return Steps_Widget(
          steps: currentSteps,
          nextAction:(){
            setState(() {
              currentSteps = Testing_steps.steps_3;
            });
          },
          backAction: (){
            setState(() {
              currentSteps = Testing_steps.steps_2_1;
            });
          },
        );
      }
      case Testing_steps.steps_3: {
        return Steps_Widget(
          steps: currentSteps,
          nextAction:(){
            setState(() {
              currentSteps = Testing_steps.steps_liquify_countDown;
            });
          },
          backAction: (){
            setState(() {
              currentSteps = Testing_steps.steps_2_2;
            });
          },
        );
      }
      case Testing_steps.steps_liquify_countDown: {
        return Steps_Widget(
          steps: currentSteps,
          nextAction:(){
            setState(() {
              currentSteps = Testing_steps.steps_4;
            });
          },
          backAction: (){
          },
        );
      }
      case Testing_steps.steps_4: {
        return Steps_Widget(
          steps: currentSteps,
          nextAction:(){
            setState(() {
              currentSteps = Testing_steps.steps_5;
            });
          },
          backAction: (){
            setState(() {
              currentSteps = Testing_steps.steps_3;
            });
          },
        );
      }
      case Testing_steps.steps_5: {
        return Steps_Widget(
          steps: currentSteps,
          nextAction:(){
            setState(() {
              currentSteps = Testing_steps.steps_testing_in_process;
            });
            captureRtspStream();
          },
          backAction: (){
            setState(() {
              currentSteps = Testing_steps.steps_4;
            });
          },
        );
      }
      case Testing_steps.steps_testing_in_process: {
        return Steps_Widget(
          steps: currentSteps,
          nextAction:(){

          },
          backAction: (){

          },
        );
      }
      default: {
        return Steps_Widget(
          steps: currentSteps,
          nextAction:(){
          },
          backAction: (){
          },
        );
      }
    }

  }




  steps_connect_widget(BuildContext context) {
    return Scrollbar(
        thickness: 6,
        radius: const Radius.circular(3),
        interactive: true,
        child: SingleChildScrollView(
            child: Container(
              margin: EdgeInsets.only(left: 20.w,right: 20.w),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [

                  Container(
                    alignment: Alignment.center,
                    child:  Image.asset('images/wifi.png',height: 250.w,width: 250.w,),
                  ),

                  Container(
                    height: 48.h,
                    width: 335.w,
                    decoration: BoxDecoration(
                      color: Color.fromRGBO(16, 37, 105, 1),
                      borderRadius: BorderRadius.circular(5.h),
                    ),
                    margin: EdgeInsets.only(top: 60.h),
                    child: TextButton(
                      onPressed: () {
                        if(_connectionStatus == DeviceConnectionState.disconnected){
                          print('-------1111');

                          retryConnect();

                        }else if(_connectionStatus == DeviceConnectionState.connected){
                          print('-------2222');
                          setState(() {
                            currentSteps = Testing_steps.steps_2_1;
                          });
                        }
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Visibility(
                            visible: _connectionStatus == DeviceConnectionState.connecting,
                              child: Container(
                                margin: EdgeInsets.only(right: 20.w),
                                width: 20.w,
                                height: 20.w,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                ),
                              ),
                          ),
                          Text(
                            _connectionStatus == DeviceConnectionState.disconnected ? 'Setup network connection' : _connectionStatus == DeviceConnectionState.connecting ? 'connecting' : "Next",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w400,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),

                  Padding(
                    padding: EdgeInsets.only( top: 20.h),
                    // 左右各16像素的边距
                    child: AspectRatio(
                      aspectRatio: 335.w / 48.h, // 设置长宽比为343:50
                      child: CommonButton(
                        // title: S.of(context).Verification,
                        bgColor: Colors.transparent,
                        title: 'BACK',
                        textColor: globalColor(),
                        borderRadius: 5.w,
                        onTap: () {

                          setState(() {
                            currentSteps = Testing_steps.steps_1;
                          });

                        },
                      ),
                    ),
                  ),

                  Padding(
                    padding: EdgeInsets.only( top: 20.h),
                    // 左右各16像素的边距
                    child: AspectRatio(
                      aspectRatio: 335.w / 48.h, // 设置长宽比为343:50
                      child: CommonButton(
                        // title: S.of(context).Verification,
                        bgColor: Colors.transparent,
                        title: '发送 已连接 指令',
                        textColor: globalColor(),
                        borderRadius: 5.w,
                        onTap: () {

                          _tcpService.sendData('RGB:0-1-0|Blink:600-200|Power:1|AutoOFF:21|PID:2.12-0.003-0|'.codeUnits);
                        },
                      ),
                    ),
                  ),

                  Padding(
                    padding: EdgeInsets.only( top: 20.h),
                    // 左右各16像素的边距
                    child: AspectRatio(
                      aspectRatio: 335.w / 48.h, // 设置长宽比为343:50
                      child: CommonButton(
                        // title: S.of(context).Verification,
                        bgColor: Colors.transparent,
                        title: '发送 检测中 指令',
                        textColor: globalColor(),
                        borderRadius: 5.w,
                        onTap: () {

                          _tcpService.sendData('RGB:1-0-0|Blink:600-200|Power:1|AutoOFF:21|PID:2.12-0.003-0|'.codeUnits);
                        },
                      ),
                    ),
                  ),

                ],
              ),
            )
        )
    );
  }

  captureRtspStream() async {
    print('--------====captureRtspStream');

    // 获取临时目录
    final tempDir = await getTemporaryDirectory();
    // 生成唯一文件名（避免冲突）

    final videoPath = '${tempDir.path}/output.mp4';

    String commond = '-i rtsp://'+ '192.168.3.1' + '/live/0 -y -t 40 -vcodec copy -acodec copy ' + videoPath;


    FFmpegKit.execute(commond).then((session) async {
      final returnCode = await session.getReturnCode();
      if (ReturnCode.isSuccess(returnCode)) {
        // SUCCESS
        print('--------实时流 复制成功');

        final saveSuccess = await VideoSaverService.saveVideoToGallery(videoPath);
        // 删除临时文件（节省空间）
        if (saveSuccess) {
          print('--------视频保存本地成功');

          // _methodChannel.invokeMethod('videoPath',videoPath);

          await basicUsage(videoPath);

          // try {
          //   await File(videoPath).delete();
          //   print('临时文件已删除: $videoPath');
          // } catch (e) {
          //   print('删除临时文件失败: $e');
          // }
        }

      } else if (ReturnCode.isCancel(returnCode)) {
        // CANCEL
      } else {
        // ERROR
      }
    });

  }

  /// 示例：基本使用
  Future<void> basicUsage(String videoPath) async {
    print('=== 基本使用示例 ===');

    // 1. 创建配置
    final config = Configuration();

    // 2. 创建Motility实例
    final motility = Motility(config: config);

    // 3. 分析视频
    if (videoPath != null) {
      print('开始分析视频: $videoPath');

      final result = await motility.analyze(videoPath);

      if (result != null) {
        Navigator.pushNamed(context, '/report_page',arguments: result);
      } else {
        print('=====分析完成！ ==== 分析失败或没有检测到精子');
      }

    } else {
      print('=====未找到示例视频文件');
    }
  }

  
}


